/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 * <p>
 * MmsSuggestionFeedbackService
 * 意见反馈表
 * <p>
 * 修改纪录
 * 2021-11-01 版本：1.0 zhangqianbo 创建。
 *
 * @version 版本：1.0
 * @author 作者：zhangqianbo
 * 创建日期：2021-11-01
 */
package com.topscomm.mms.service.impl;

import com.topscomm.basic.exception.ServiceException;
import com.topscomm.cbo.pojo.CboApprovalNodeEntity;
import com.topscomm.cbo.pojo.CboApprovalNodeInsEntity;
import com.topscomm.cbo.service.ICboMessageAppService;
import com.topscomm.cbo.service.ICboMessageSysService;
import com.topscomm.mms.MmsSystemConst;
import com.topscomm.mms.pojo.MmsResponseEntity;
import com.topscomm.mms.pojo.MmsSuggestionFeedbackEntity;
import com.topscomm.mms.service.IMmsBaseConfigService;
import com.topscomm.mms.service.IMmsResponseService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.Query;
import com.topscomm.sys.ISysService;
import com.topscomm.sys.SysService;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.TapService;
import com.topscomm.tap.common.DatacodeCache;
import com.topscomm.tap.common.FlowDatacodeCache;
import com.topscomm.tap.common.ParameterCache;
import com.topscomm.tap.common.SessionUserBean;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.topscomm.mms.service.IMmsSuggestionFeedbackService;
import com.topscomm.mms.service.impl.auto.MmsSuggestionFeedbackServiceAuto;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service(value = "mmsSuggestionFeedbackService")
@Scope(value = "singleton")
public class MmsSuggestionFeedbackService extends MmsSuggestionFeedbackServiceAuto implements IMmsSuggestionFeedbackService {

    FlowDatacodeCache flowDatacodeCache = new FlowDatacodeCache();
    protected List<Map<String, Object>> flowIdList = new ArrayList();

    @Autowired
    public IMmsResponseService mmsResponseService;

    @Override
    protected void beforeSubmit(TapEntity entity, SessionUserBean sessionUserBean) {
        super.beforeSubmit(entity, sessionUserBean);
        MmsSuggestionFeedbackEntity mmsSuggestionFeedbackEntity = (MmsSuggestionFeedbackEntity) entity;
        this.flowIdList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_MmsSuggestionFeedback",
                mmsSuggestionFeedbackEntity.getApplyusercode(), "sortcode");
        if (flowIdList.size() > 0) {
            mmsSuggestionFeedbackEntity.setFlowid(ConvertUtil.convertToLong(flowIdList.get(0).get("id")));
        } else {
            throw new ServiceException("没有匹配的审批流，请联系管理员！");
        }
    }

    @Override
    protected void afterSubmit(TapEntity entity, SessionUserBean sessionUserBean) {
        super.afterSubmit(entity, sessionUserBean);
        try {
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendLineSingle("update CboApprovalFlowIns set ");
            sql.appendLineSingle("extendfield1 = (select docno from {0} "
                    + "where CboApprovalFlowIns.sourceid = {0}.id "
                    + "and CboApprovalFlowIns.sourcetype = '{0}'),", entity.getTableName());
            sql.appendLineSingle("extendfield2 = (select deptcode from {0} "
                    + "where CboApprovalFlowIns.sourceid = {0}.id "
                    + "and CboApprovalFlowIns.sourcetype = '{0}'),", entity.getTableName());
            sql.appendLineSingle("extendfield3 = (select usercode from {0} "
                    + "where CboApprovalFlowIns.sourceid = {0}.id "
                    + "and CboApprovalFlowIns.sourcetype = '{0}')", entity.getTableName());
            sql.appendLineSingle("where sourceid = '{0}' and sourcetype='{1}'", entity.getId(), entity.getTableName());
            this.getDao().updateExecute(sql.toString());
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }




    /**
     * @author: zhangqianbo
     * @date: 2021-11-01
     * @param paraMap
     * @return
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    public String spellListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" 1=1 ");
        if (paraMap.containsKey("qry_name")) {
            String value = paraMap.get("qry_name").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and name like '%{0}%' ", value);
        }
        if (paraMap.containsKey("qry_code")) {
            String value = paraMap.get("qry_code").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and applyusercode = '{0}' ", value);
        }
        // 从流程文档进入的意见反馈模块只查询流程文档相关的意见反馈，否则查询全部意见反馈（包括流程文档）
        if (paraMap.containsKey("systemFlag")) {
            String value = paraMap.get("systemFlag").toString();
            if(!StringUtils.isEmpty(value)) {
                sql.appendSingle("and system = '{0}'", value);
            }
        }
        if (paraMap.containsKey("ispublic")) {
            String value = paraMap.get("ispublic").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and ispublic = '{0}' ", value);
        }
        if (paraMap.containsKey("qry_key")) {
            String value = paraMap.get("qry_key").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and content like '%{0}%' ", value);
        }
        if (paraMap.containsKey("feedbackState")) {
            String value = paraMap.get("feedbackState").toString();
            if (!StringUtil.isEmpty(value) && value.equals("9")) {
                sql.appendSingle(" and state = '9' ");
            }
        }
        return sql.toString();
    }

    /**
     * @author: zhangqianbo
     * @date:
     * @description:查询办理历史
     * @modify:
     */
    public int queryFeedbackHistory(Map<String, Object> paraMap, List<Map<String, Object>> tempList) {
        Query query = new Query(paraMap);
        int totalCount = this.getCount1(paraMap, "queryFeedbackHistory");
        List<Map<String, Object>> resultList = null;
        if (query.getPageSize() > 0) {
            paraMap.put("IsNeedPage", true);
            // 分页拦截处理
            int beginCount = query.getCurrentPage() * query.getPageSize() - query.getPageSize();
            paraMap.put("begincount", beginCount);
            paraMap.put("pagesize", query.getPageSize());
            resultList = this.queryMapForPage(paraMap, "queryFeedbackHistory");
        } else {
            resultList = this.queryMap(paraMap, "queryFeedbackHistory");
        }
        tempList.addAll(resultList);
        return totalCount;
    }

    /**
     * @author: zhangqianbo
     * @date:
     * @description:反馈列表
     * @modify:
     */
    public int queryFeedbackList(Map<String, Object> paraMap, List<Map<String, Object>> tempList) {
        Query query = new Query(paraMap);
        int totalCount = 0;
        List<Map<String, Object>> resultList = null;
        // 反馈列表
        StringBufferProxy sqlWhere = new StringBufferProxy();
        // 当前用户角色
        String roleCode = ConvertUtil.convertToString(paraMap.get("rolecode"));
        if (StringUtil.isEmpty(roleCode)) {
            return 0;
        }
        if ("manager".equals(roleCode)) {
            // 系统管理员
            sqlWhere.appendSingle("state = 9");
        } else if ("systemresponsible".equals(roleCode)) {
            // 系统负责人
            List<String> systemCodeList = Arrays.asList(ConvertUtil.convertToString(paraMap.get("systemcodes")).split(","));
            String systemCodes = systemCodeList.stream().map(item -> "'" + item + "'").collect(Collectors.joining(","));
            sqlWhere.appendSingle("state = 9 and system in ({0})", systemCodes);
        }
        if (paraMap.containsKey("qry_key")) {
            String value = paraMap.get("qry_key").toString();
            if (!StringUtil.isEmpty(value))
                sqlWhere.appendSingle(" and content like '%{0}%' ", value);
        }
        // 该变量存入时由从流程文档进入该待办页面时传入，存在该变量时只查询和流程文档相关的待办列表，否则查询全部待办列表
        if (paraMap.containsKey("systemFlag")){
            String value = paraMap.get("systemFlag").toString();
            if(!StringUtils.isEmpty(value)){
                sqlWhere.appendSingle("and system = '{0}'", value);
            }
        }
        totalCount = this.getCount(sqlWhere.toString());
        if (query.getPageSize() > 0) {
            if ("feedback.submitdate".equals(query.getSidx())) {
                query.setSidx("submitdate");
            }
            resultList = this.queryMapForPage(sqlWhere.toString(), query.getCurrentPage(),
                    query.getPageSize(), query.getSidx(), query.getSord());
        } else {
            resultList = this.queryMapByWhere(sqlWhere.toString());
        }
        tempList.addAll(resultList);
        return totalCount;
    }

    /**
     * @author: zhangqianbo
     * @date:
     * @description:我的反馈和反馈广场列表
     * @modify:
     */
    public int queryMyFeedback(Map<String, Object> paraMap, List<Map<String, Object>> tempList) {
        Query query = new Query(paraMap);
        List<Map<String, Object>> resultList = null;
        String sqlWhere = this.spellListSql(paraMap);
        int totalCount = this.getCount(sqlWhere);
        if (query.getPageSize() > 0) {
            resultList = this.queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), "");
        } else {
            resultList = this.queryMapByWhere(sqlWhere);
        }
        tempList.addAll(resultList);
        return totalCount;
    }


    /**
     * @author: zhangqianbo
     * @date:
     * @description:查询回复表sql
     * @modify:
     */
    public void queryFeedbackResponse(List<Map<String, Object>> tempList) {

        StringBufferProxy str = new StringBufferProxy();
        str.appendSingle("sourceid in (");
        for (Map<String, Object> tempMap : tempList) {
            str.appendSingle("{0},", tempMap.get(MmsSuggestionFeedbackEntity.FieldId));
        }
        StringBufferProxy substring = str.substring(0, str.length() - 1);
        substring.appendSingle(") ORDER BY CREATEON DESC");
        List<MmsResponseEntity> mmsResponseEntityList = this.mmsResponseService.queryByWhere(substring.toString());
        Map<Long, List<MmsResponseEntity>> listMap = new HashMap<>();
        if (mmsResponseEntityList.size() > 0) {
            listMap = mmsResponseEntityList.stream().collect(Collectors.groupingBy(MmsResponseEntity::getSourceid));
        }
        // 把回复放在意见反馈中
        for (Map<String, Object> tempMap : tempList) {
            List<MmsResponseEntity> tempMmsResponseEntityList = listMap.get(ConvertUtil.convertToLong(tempMap.get(MmsSuggestionFeedbackEntity.FieldId)));
            if (tempMmsResponseEntityList != null && tempMmsResponseEntityList.size() > 0) {
                tempMap.put("response", tempMmsResponseEntityList.get(0));
            } else {
                tempMap.put("response", "");
            }
        }
    }


    @Override
    public void setDispFields(Map<String, Object> mapRow, DatacodeCache datacodeCache) {
        super.setDispFields(mapRow, datacodeCache);
        String temp;
        if (mapRow.get("system") != null) {
            temp = mapRow.get("system").toString();
            mapRow.put("dispsystem", datacodeCache.getValueDynamic("FeedbackSystem", temp, "code", "name"));
        }
    }
}
